/*
 * Copyright (c) 2024. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.school_admin.controller;

import com.school_admin.config.Result;
import com.school_admin.entity.WangEditor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("video")
public class VideoController {
    private static final String UPLOAD_DIR = "C:/Users/31774/Desktop/school_admin/src/main/resources/static/image";


    @PostMapping("/upload")
    public Object upload(MultipartFile file) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty()) {
            return Result.success("1", "文件不能为空");
        }
        try {
            byte[] bytes = file.getBytes();
            // 生成当前日期
            LocalDateTime currentTime = LocalDateTime.now();
            // 日期格式化
//            String formattedDate = currentTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 生成时间戳
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            // 将文件保存到指定目录
            Path path = Paths.get(UPLOAD_DIR + File.separator + fileName);
            Files.write(path, bytes);
            Map<String, String> map = new HashMap<>();
            map.put("url", "http://localhost:8081/image/" + fileName);
            return new WangEditor<>(0, map);
        } catch (IOException e) {
            return new WangEditor<>(1, "上传失败");
        }
    }
}
